<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree v-bind:tree-data="treeData" v-on:appTreeClick="treeClickHandle"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              姓名：<el-input placeholder="请输入内容" v-model="queryData.name" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              性别：
              <el-select v-model="queryData.sex" clearable placeholder="请选择" filterable>
                <el-option v-for="(item,index) in genderOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              政治面貌：
              <el-select v-model="queryData.politicsStatus" clearable placeholder="请选择" filterable>
                <el-option v-for="(item,index) in politicalStatusOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              学历：
              <el-cascader
                v-model="queryData.educationArr"
                placeholder="请选择"
                :options="educationOption"
                filterable
                :props="dictProps"
                clearable
                :show-all-levels="false">
              </el-cascader>
            </div>
            <div>
              职务：
              <el-select v-model="queryData.titleName" placeholder="请选择" clearable>
                <el-option v-for="(item,index) in titleNameOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              年龄段：
              <el-date-picker
                v-model="queryData.startTime"
                value-format="timestamp"
                format="yyyy 年 MM 月 dd 日"
                placeholder="选择日期时间"
                :picker-options="dataPickerBeforeTodayOptions">
              </el-date-picker><span> ~ </span>
              <el-date-picker
                v-model="queryData.endTime"
                value-format="timestamp"
                format="yyyy 年 MM 月 dd 日"
                placeholder="选择日期时间"
                :picker-options="dataPickerBeforeTodayOptions">
              </el-date-picker>
              &nbsp;
            </div>
            <div>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table
          :page-data="pageData"
          :table-columns="tableColumns"
          v-on:currentChange="handleCurrentChange"
          v-on:handleCheckedRows="handleCheckedRows"/>
          <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" :before-close="cancel">
            <el-form :model="formData"
             :rules="rules"
             ref="formData"
             :disabled="showOnly"
             label-width="120px"
             size="mini">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="部门：" prop="deptIdArr">
                    <div class="block">
                      <el-cascader
                        placeholder="请选择"
                        :options="treeData"
                        clearable
                        filterable
                        :props="areaProps"
                        change-on-select
                        :show-all-levels="false"
                        v-model="formData.deptIdArr"
                        @change="deptChangedEvt">
                      </el-cascader>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="账号：" prop="username">
                    <el-input v-model="formData.username" placeholder="请输入账号"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="姓名：" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入姓名"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="身份证号：" prop="idCardNumber">
                    <el-input v-model="formData.idCardNumber" placeholder="请输入身份证号"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="性别：">
                    <el-select v-model="formData.sex" clearable placeholder="请选择" filterable>
                      <el-option v-for="(item,index) in genderOption" :key="index" :label="item.name" :value="item.code"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="工号：">
                    <el-input v-model="formData.jobNumber" placeholder="请输入工号"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="电话：">
                    <el-input v-model="formData.phone" placeholder="请输入电话"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="邮箱：">
                    <el-input v-model="formData.email" placeholder="请输入邮箱"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="联系地址：">
                    <el-input v-model="formData.address" placeholder="请输入联系地址"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="政治面貌：">
                    <el-select v-model="formData.politicsStatus" clearable placeholder="请选择" filterable>
                      <el-option v-for="(item,index) in politicalStatusOption" :key="index" :label="item.name" :value="item.code"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="职务：">
                    <el-select v-model="formData.titleName" placeholder="请选择职务" clearable>
                      <el-option v-for="(item,index) in titleNameOption" :key="index" :label="item.name" :value="item.code"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="文化程度：">
                    <el-cascader
                      v-model="formData.educationArr"
                      placeholder="请选择"
                      :options="educationOption"
                      filterable
                      :props="dictProps"
                      clearable
                      change-on-select>
                    </el-cascader>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="是否启用：" prop="disableStatus">
                    <el-select v-model="formData.disableStatus" placeholder="请选择是否启用" clearable>
                      <el-option label="是" :value="1"></el-option>
                      <el-option label="否" :value="0"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-if="isRoleListShow">
                  <el-form-item label="选择角色：">
                    <el-checkbox-group v-model="roleIdList">
                      <el-checkbox v-for="item in allRoleData" :key="item.id" :label="item.id">{{item.roleName}}</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div v-if="!showOnly" slot="footer" class="dialog-footer">
              <el-button @click="cancel('formData')">取 消</el-button>
              <el-button type="primary" @click="save('formData')">提 交</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import BtnGroup from '@/components/BtnGroup'
import AppTable from '@/components/AppTable'
import {getAllRegion} from '@/utils/region'
import {getUserDeptTree} from '@/utils/SessionDataUtil'
import {getDictDataOption} from '@/utils/getDictDataOption'
import {findDeptMember, createUser, updateUser, deleteUser, getUser, listRoleByCurUser} from '@/http/AppApi'
import {validateIdefer} from '@/utils/validate'
export default {
  data () {
    return {
      tableData: [],
      treeData: [],
      pageData: {},
      queryData: {},
      formData: {
        disableStatus: 1
      },
      areaProps: {
        label: 'name',
        value: 'id'
      },
      dictProps: {
        label: 'name',
        value: 'code'
      },
      dialogTitle: '',
      allDeptData: [],
      allRoleData: [],
      roleIdList: [],
      dialogFormVisible: false,
      isRoleListShow: false,
      currentSelectedData: [],
      showOnly: false,
      tableColumns: [
        { label: '账号', prop: 'username' },
        { label: '姓名', prop: 'name' },
        { label: '所属部门', prop: 'departmentName' },
        { label: '电话', prop: 'phone' },
        { label: '最后登陆时间', prop: 'lastLoginTime', formatter: this.formatterColumn }
      ],
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      rules: {
        deptIdArr: [{
          required: true,
          message: '请选择部门',
          trigger: 'blur'
        }],
        username: [{
          required: true,
          message: '请输入账号',
          trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '请输入姓名',
          trigger: 'blur'
        }],
        idCardNumber: [{
          required: true,
          validator: validateIdefer,
          message: '请输入有效身份证号',
          trigger: 'blur'
        }],
        disableStatus: [{
          required: true,
          message: '请选择是否启用',
          trigger: 'blur'
        }]
      },
      genderOption: [],
      levelOption: [],
      titleNameOption: [],
      educationOption: [],
      politicalStatusOption: []
    }
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable
  },
  mounted () {
    this.getTableData()
    this.getTreeData()
    this.genderOption = getDictDataOption('性别')
    this.titleNameOption = getDictDataOption('人员职务')
    this.educationOption = getDictDataOption('学历')
    this.politicalStatusOption = getDictDataOption('政治面貌')
  },
  methods: {
    deptChangedEvt (val) {
      if (val && val.length > 0) {
        this.isRoleListShow = true
        let len = val.length - 1
        let param = {
          departmentId: val[len]
        }
        this.getAllRoleData(param)
      } else this.isRoleListShow = false
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.formData.roleIdList = this.roleIdList
          if (this.formData.deptIdArr && this.formData.deptIdArr.length > 0) {
            let len = this.formData.deptIdArr.length - 1
            this.$set(this.formData, 'departmentId', this.formData.deptIdArr[len])
          } else {
            this.$set(this.formData, 'departmentId', '')
          }
          this.formData.education = this.formData.educationArr ? this.formData.educationArr.join(',') : ''
          if (this.formData.id) {
            updateUser(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.getTableData()
                this.$message({
                  showClose: true,
                  message: '修改成功',
                  type: 'success'
                })
              }
            })
          } else {
            createUser(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.dialogFormVisible = false
                this.$refs[formName].resetFields()
                this.$message({
                  showClose: true,
                  message: '新增成功',
                  type: 'success'
                })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteUser(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.$message({
                  showClose: true,
                  message: '删除成功',
                  type: 'success'
                })
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel (formName) {
      this.showOnly = false
      this.isRoleListShow = false
      this.dialogFormVisible = false
      this.roleIdList = []
      this.formData = {}
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
    },
    getTableData () {
      let param = this.queryData
      findDeptMember(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.pageData = data
            if (this.pageData.items && this.pageData.items instanceof Array) {
              this.tableData = this.pageData.items
            }
          }
        }
      })
    },
    handleCurrentChange (val) {
      this.queryData.offset = (val - 1) * 10
      this.getTableData()
    },
    getAllRoleData (param) {
      listRoleByCurUser(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data && data instanceof Array) {
            if (data.length === 0) this.isRoleListShow = false
            this.allRoleData = data
          }
        }
      })
    },
    getTreeData () {
      let data = getUserDeptTree()
      if (data && data instanceof Array) {
        this.treeData = data
      }
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        if (callbackData.btnType === 'post') {
          if (this.formData.deptIdArr && this.formData.deptIdArr.length > 0) {
            let arr = this.formData.deptIdArr
            this.formData = {}
            this.$set(this.formData, 'deptIdArr', arr)
            this.$set(this.formData, 'disableStatus', 1)
          }
        } else {
          let obj = JSON.stringify(callbackData.rows[0])
          this.formData = JSON.parse(obj)
          let educationArr = this.formData.education !== '' && this.formData.education !== null ? this.formData.education.split(',') : []
          this.$set(this.formData, 'educationArr', educationArr)
          let deptData = {}
          deptData.id = this.formData.departmentId
          deptData.items = this.treeData
          let deptIdArr = getAllRegion(deptData)
          this.$set(this.formData, 'deptIdArr', deptIdArr)
          this.roleIdList = this.formData.roleIdList ? this.formData.roleIdList : []
          this.deptChangedEvt(deptIdArr)
          this.isRoleListShow = true
        }
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        let m = this
        getUser(rows[0].userId).then(resp => {
          if (resp.code && resp.code === '200') {
            let data = resp.data
            if (data) {
              m.currentSelectedData = [data]
              m.formData = data
            }
          }
        })
      } else {
        this.currentSelectedData = []
        this.formData = {}
      }
    },
    treeClickHandle (data) {
      if (this.queryData.educationArr && this.queryData.educationArr.length > 0) {
        let len = this.queryData.educationArr.length - 1
        this.queryData.education = this.queryData.educationArr[len]
        delete this.queryData.educationArr
      }
      this.queryData.deptId = data.id
      this.queryData.offset = 0
      let deptData = {}
      deptData.id = data.id
      deptData.items = this.treeData
      let deptIdArr = getAllRegion(deptData)
      this.$set(this.formData, 'deptIdArr', deptIdArr)
      this.deptChangedEvt(deptIdArr)
      this.getTableData()
    },
    searchHandleClick () {
      if (this.queryData.educationArr && this.queryData.educationArr.length > 0) {
        let len = this.queryData.educationArr.length - 1
        this.queryData.education = this.queryData.educationArr[len]
        delete this.queryData.educationArr
      }
      this.queryData.offset = 0
      this.getTableData()
    },
    formatterColumn (row, column) {
      if (row && row.lastLoginTime) {
        let time = row.lastLoginTime
        return this.$moment(time).format('YYYY-MM-DD HH:mm')
      } else {
        return '未登录'
      }
    }
  },
  computed: {},
  watch: {}
}
</script>
<style scoped>
</style>
